// src/stores/tagsView.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTagsViewStore = defineStore('tagsView', () => {
  const visitedViews = ref([]) // [{ name, path, fullPath, title, affix, meta, query, params }]
  const cachedViews = ref([])   // [ component name ]

  // —— Helpers ——
  const viewKeyEq = (a, b) => (a.path === b.path || a.fullPath === b.fullPath)

  const normalize = (view) => ({
    name: view.name,
    path: view.path,
    fullPath: view.fullPath || view.path,
    title: view.title || view.meta?.title || view.name || 'No Title',
    affix: !!view.affix,
    meta: view.meta || {},
    query: view.query,
    params: view.params
  })

  // —— Add ——
  const addVisitedView = (view) => {
    const v = normalize(view)
    if (!visitedViews.value.some(x => viewKeyEq(x, v))) {
      visitedViews.value.push(v)
    } else {
      // 同路径更新 title/affix（避免旧数据）
      visitedViews.value = visitedViews.value.map(x => viewKeyEq(x, v) ? { ...x, ...v } : x)
    }
  }

  const addCachedView = (view) => {
    const name = view.name
    if (!name) return
    if (cachedViews.value.includes(name)) return
    if (view.meta?.keepAlive) cachedViews.value.push(name)
  }

  const addView = (view) => {
    addVisitedView(view)
    addCachedView(view)
  }

  // —— Delete ——
  const delVisitedView = (view) => {
    const before = visitedViews.value.length
    visitedViews.value = visitedViews.value.filter(v => !viewKeyEq(v, view) || v.affix)
    return before !== visitedViews.value.length
  }

  const delCachedView = (view) => {
    const name = view.name
    if (!name) return false
    const idx = cachedViews.value.indexOf(name)
    if (idx > -1) {
      cachedViews.value.splice(idx, 1)
      return true
    }
    return false
  }

  const delView = async (view) => {
    delVisitedView(view)
    delCachedView(view)
    return { visitedViews: visitedViews.value.slice(), cachedViews: cachedViews.value.slice() }
  }

  const delOthersViews = async (view) => {
    const v = normalize(view)
    visitedViews.value = visitedViews.value.filter(x => x.affix || viewKeyEq(x, v))
    cachedViews.value = v.name ? cachedViews.value.filter(n => n === v.name) : []
    return { visitedViews: visitedViews.value.slice(), cachedViews: cachedViews.value.slice() }
  }

  const delAllViews = async () => {
    visitedViews.value = visitedViews.value.filter(v => v.affix)
    cachedViews.value = []
    return { visitedViews: visitedViews.value.slice(), cachedViews: cachedViews.value.slice() }
  }

  // —— Ensure affix tags（用于初始化固定标签，如 /dashboard）——
  const ensureAffix = (affixList = []) => {
    affixList.forEach(tag => {
      addVisitedView({ ...tag, affix: true })
    })
  }

  return {
    visitedViews,
    cachedViews,
    addView,
    addVisitedView,
    addCachedView,
    delView,
    delVisitedView,
    delCachedView,
    delOthersViews,
    delAllViews,
    ensureAffix
  }
})